package cn.pku.ss.fa.sessionbean;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.*;

import cn.pku.ss.fa.entity.*;

import java.util.*;

import cn.pku.ss.fa.bean.*;
import cn.pku.ss.fa.entity.events.*;

@Stateless
@Local ({BoardManagerLocal.class})
public class BoardManager implements BoardManagerLocal {

	@PersistenceContext
	protected EntityManager manager;
	
	public List<BoardMessageBean> getBoardMessagesByUserId(int userId) {
		User user = manager.find(User.class, userId);
		Set<Board> boards = user.getBoards();
		
		List<BoardMessageBean> list = new ArrayList<BoardMessageBean>();
		for (Iterator iter = boards.iterator(); iter.hasNext(); ) {
			Board board = (Board)iter.next();
			BoardMessageBean bean = this.convertBoardToBoardMessageBean(board);
			list.add(bean);
		}
		return list;
	}
	
	private BoardMessageBean convertBoardToBoardMessageBean(Board board) {
		BoardMessageBean bean = new BoardMessageBean();
		bean.setContent(board.getContent());
		bean.setCreateTime(String.valueOf(board.getCreateTime()));
		bean.setFromRealName(board.getFromRealName());
		bean.setFromUserId(board.getFromUserId());
		
		User fromUser = manager.find(User.class, board.getFromUserId());
		
		bean.setFromUserimage(fromUser.getImageURL());
		bean.setToUserId(board.getUser().getId());
		
	    return bean;
	}
	
	public void leaveMessage(BoardMessageBean message) {
		User toUser = manager.find(User.class, message.getToUserId());
		User fromUser = manager.find(User.class, message.getFromUserId());
		
		Board board = new Board();
		board.setContent(message.getContent());
		board.setCreateTime(new Date());
		board.setFromUserId(message.getFromUserId());
		board.setFromRealName(fromUser.getRealName());
		board.setUser(toUser);
		
		toUser.getBoards().add(board);
		
		manager.persist(board);
		
	}
}
